package com.firegod.student.service;

import com.alibaba.fastjson.JSONObject;
import com.firegod.commonutils.result.ResultCode;
import com.firegod.servicebase.dao.UserRepository;
import com.firegod.servicebase.entity.Course;
import com.firegod.servicebase.entity.Student;
import com.firegod.servicebase.entity.Teacher;
import com.firegod.servicebase.entity.User;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.shiro.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenService tokenService;

    public Map<String, Object> getUserInfo(String userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User user = userRepository.getByUserId(userId);
        if (user == null) {
            throw GuliException.from(ResultCode.USER_NOT_EXIST);
        }
        hashMap.put("isTea", user instanceof Teacher);
        hashMap.put("userId", userId);
        hashMap.put("name", user.getName());
        hashMap.put("email", user.getEmail());
        hashMap.put("mobile", user.getMobile());
        if (user instanceof Teacher) {
            Teacher teacher = (Teacher) user;
            hashMap.put("courseList", teacher.getCourseList().stream().map(Course::show).toArray(JSONObject[]::new));
        } else {
            Student student = (Student) user;
            hashMap.put("courseList", student.getCourseList().stream().map(Course::show).toArray(JSONObject[]::new));
        }

        return hashMap;
    }

    public void logout() {
        String studentId = tokenService.getCurrentUser();
        tokenService.deleteToken(studentId);
    }
}
